package cn.findviewbydream.evil.main.utils;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;

/********************************************
 * 工程名：MealOrder
 * 包名：cn.findviewbydream.evil.main.utils
 * 时间：17-2-23
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：文件写入类
 ********************************************/
public class FileWrite
{
    public static void write(CommonsMultipartFile file, String path, String fileName) throws IOException
    {
        new FileWrite().writeFile(file, path, fileName);
    }

    public static void write(CommonsMultipartFile file, String path) throws IOException
    {
        new FileWrite().writeFile(file, path, null);
    }

    private void writeFile(CommonsMultipartFile file, String path, String fileName) throws IOException
    {
        makeDir(path);

        InputStream inputStream = file.getInputStream();
        OutputStream outputStream;
        if (fileName == null)
            outputStream = new FileOutputStream(new File(path, file.getOriginalFilename()));
        else
            outputStream = new FileOutputStream(new File(path, fileName));
        int len;
        byte[] buffer = new byte[10240];
        while ((len = inputStream.read(buffer)) != -1)
        {
            outputStream.write(buffer, 0, len);
        }
        inputStream.close();
        outputStream.close();
    }

    private boolean makeDir(String path)
    {
        File file = new File(path);
        return !file.exists() && !file.isDirectory() && file.mkdirs();
    }
}